<template>
    <div style="width: 100%;">
        <!-- 选择框 -->
        <el-select v-model="isShowRoomGroup" placeholder="请选择" style="float: left; margin-right: 10px;">
            <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
       
        <!-- 搜索框 -->
        <el-input
                v-model="studentSearch"
                size="normal"
                placeholder="输入学生学号"
                style="width: 200px;float: left;"/>
        
        <!-- 搜索按钮 -->
        <el-button type="primary" size="normal" @click="handleSearchStudent" style="float: left; margin-left: 20px;">搜索</el-button>
        
        <!-- 重置搜索 -->
        <el-button type="primary" size="normal" @click="isSearchStudent = false; studentSearch = ''" style="float: left; margin-left: 20px;">重置搜索</el-button>
       
        <!-- 添加学生 -->
        <el-button type="primary" size="default" @click="AddDialogFormVisible=true" style="float: right;">添加学生</el-button>
        
        <!-- 按宿舍展示信息 -->
        <el-table 
        :data="roomDataFilters" 
        style="width: 100%;" 
        border
        stripe
        highlight-current-row 
        height="600"
        v-show="isShowRoomGroup && !isSearchStudent"
        >
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-table :data="props.row.stuList" border stripe style="width: 95%;margin-left: 3%;" size="normal">
                        <el-table-column
                            prop="studyNumber"
                            label="学号"
                            min-width="120"
                            >
                        </el-table-column>
                        <el-table-column
                            prop="name"
                            label="姓名"
                            min-width="120">
                        </el-table-column>
                        <el-table-column
                            prop="faculty"
                            label="学院"
                            min-width="120">
                        </el-table-column>
                        <el-table-column
                            prop="phoneNumber"
                            label="电话号码"
                            min-width="120">
                        </el-table-column>
                        <el-table-column
                        label="操作"
                        min-width="200"
                        >
                            <template slot-scope="scope">
                                <el-button
                                size="mini"
                                @click="handleEdit(scope.$index,props.row, scope.row)">编辑</el-button>
                                <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>
            </el-table-column>
            <el-table-column
            prop="address"
            label="宿舍楼栋"
            min-width="120"
            align="center"
            :filters="addressFiltersArr"
            :filter-method="addressFilterHandler">
            </el-table-column>
            <el-table-column
            prop="door"
            label="门牌号"
            min-width="120"
            align="center">
            </el-table-column>
        </el-table>

        <!-- 按学生展示结果 -->
        <el-table :data="studentInfo"         
        style="width: 100%;" 
        border
        stripe
        highlight-current-row 
        height="600" 
        v-show="!isSearchStudent&&!isShowRoomGroup"
        >
            <el-table-column
                prop="studyNumber"
                label="学号"
                min-width="120"
                >
            </el-table-column>
            <el-table-column
                prop="name"
                label="姓名"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="faculty"
                label="学院"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="phoneNumber"
                label="电话号码"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="address"
                label="楼栋"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="door"
                label="门牌号"
                min-width="120">
            </el-table-column>
            <el-table-column
            label="操作"
            min-width="200">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    @click="handleEditStudent(scope.$index,scope.row)">编辑</el-button>
                    <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 按搜索展示结果 -->
        <el-table :data="searchStudentData"         
        style="width: 100%;" 
        border
        stripe
        highlight-current-row 
        height="600" 
        v-if="isSearchStudent"
        >
            <el-table-column
                prop="studyNumber"
                label="学号"
                min-width="120"
                >
            </el-table-column>
            <el-table-column
                prop="name"
                label="姓名"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="faculty"
                label="学院"
                min-width="120">
            </el-table-column>
            <el-table-column
                prop="phoneNumber"
                label="电话号码"
                min-width="120">
            </el-table-column>
            <el-table-column
            label="操作"
            min-width="200">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    @click="handleEditStudent(scope.$index,scope.row)">编辑</el-button>
                    <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑学生信息弹出框 -->
        <el-dialog title="学生信息" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="form" label-position="left" :hide-required-asterisk="true">
                <el-form-item label="学号" prop="studyNumber" >
                    <el-input v-model="form.studyNumber" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="学院" prop="faculty">
                    <el-input v-model="form.faculty"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phoneNumber">
                    <el-input v-model="form.phoneNumber"></el-input>
                </el-form-item >
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="门牌号" prop="door">
                    <el-input v-model="form.door"></el-input>
                </el-form-item> 
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="handleConfirm">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 添加学生信息弹出框 -->
        <el-dialog title="添加学生信息" :visible.sync="AddDialogFormVisible">
            <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" class="form" label-position="left" :hide-required-asterisk="true">
                <el-form-item label="学号" prop="studyNumber" >
                    <el-input v-model="addForm.studyNumber"></el-input>
                </el-form-item>
                <el-form-item label="学院" prop="faculty">
                    <el-input v-model="addForm.faculty"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phoneNumber">
                    <el-input v-model="addForm.phoneNumber"></el-input>
                </el-form-item >
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address"></el-input>
                </el-form-item>
                <el-form-item label="门牌号" prop="door">
                    <el-input v-model="addForm.door"></el-input>
                </el-form-item> 
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="handleAddStudent">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 分页框 -->
        <div class="block">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20 ,50, 100,200,400]"
            v-model:page-size="pageSize"
            layout="sizes,total,prev, pager, next, jumper"
            :total="totalSize">
            </el-pagination>

        </div>
    </div>
</template>

<script>
import { mapGetters,mapState } from 'vuex';
export default {
    name: 'RoomShowView',
    computed:{
        ...mapState(['searchStudentData','studentInfo','totalSize']),
        ...mapGetters(['roomData']),
        // 数据总量
        // 宿舍楼栋筛选项
        addressFiltersArr(){
            const arr = []
            this.roomData.forEach(element => {
                let item = {text:element.address,value:element.address}
                if(arr.indexOf(item) === -1){
                    arr.push(item)
                }
            })
            let len = arr.length
            for (let i = 0; i < len; i++) {
                for (let j = i + 1; j < len; j++) {
                if (arr[i].text === arr[j].text) {
                    arr.splice(j, 1)
                    len-- // 减少循环次数提高性能
                    j-- // 保证j的值自加后不变
                }
                }
            }
            return arr
        },
        // 搜索
        roomDataFilters(){
            const arr = this.roomData.filter(r => r.address.indexOf(this.addressSearch) != -1)
            return arr.filter(r => r.door.indexOf(this.doorSearch) != -1)
        },
        
    },
    methods:{
        // 分页大小改变
        handleSizeChange(val){
            this.pageSize = val
            this.$store.dispatch('getStudentInfo',{pageSize:this.pageSize,pageIndex:this.currentPage}).then(res=>{
                if(!res){
                    this.$message({
                            message: '获取信息失败，请重试！',
                            type: 'error',  
                        }) 
                }
            })
            console.log('单页条数',this.pageSize)
        },
        // 分页页数改变
        handleCurrentChange(val){
            this.currentPage = val
            this.$store.dispatch('getStudentInfo',{pageSize:this.pageSize,pageIndex:this.currentPage}).then(res=>{
                if(!res){
                    this.$message({
                            message: '获取信息失败，请重试！',
                            type: 'error',  
                        }) 
                }
            })
            console.log('当前页数',this.currentPage)
        },
        // 楼栋处理
        addressFilterHandler(val,row,col){
            const property = col['property']
            return row[property] === val
        },
        // 编辑按钮按宿舍处理
        handleEdit(index,pRow,sRow){
            this.dialogFormVisible = true
            this.form = {address:pRow.address,door:pRow.door,...pRow.stuList[index]} 
        }
        ,
        // 编辑按钮按学生和搜索
        handleEditStudent(index,row){
            this.dialogFormVisible = true
            this.form = {...row}
        },
        // 删除学生
        handleDelete(index,row){
            this.$confirm('此操作将永久删除该学生信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$store.dispatch('deleteStudent',row.studyNumber).then(res=>{
                    if(res){
                        this.$message({
                            message: '删除学生成功',
                            type: 'success',
                        })
                    }else{
                        this.$message({
                            message: '删除学生失败',
                            type: 'error',
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                type: 'info',
                message: '已取消删除'
                });          
            })
        },
        // 搜索学生
        handleSearchStudent(){
            console.log('搜索')
            if(this.studentSearch !== '')
            {
                this.$store.dispatch('searchStudent',this.studentSearch).then(res=>{
                    if(res){
                        this.isSearchStudent = true
                    }else{
                        this.$message({
                            message: '未搜索到学生',
                            type: 'error',
                        })
                    }
                })
            }else{
                this.isSearchStudent = false
            }

        },
        // 添加学生
        handleAddStudent(){
            this.$refs['addForm'].validate(valid=>{
                if(valid){
                    this.$store.dispatch('addStudent',this.addForm).then(res=>{
                        if(res){
                            this.$message({
                                message: '添加学生成功',
                                type: 'success',  
                            }) 
                            this.AddDialogFormVisible = false
                            this.addForm = {}
                        }else(
                            this.$message({
                                message: '添加学生失败',
                                type: 'error',
                            })
                        )
                    })
                }else{
                    this.$message({
                            message: '请输入正确的数据',
                            type: 'error',
                        })
                    return false
                }

            })
        },
        // 弹出框取消
        handleCancel(){
            this.dialogFormVisible = false
            this.AddDialogFormVisible = false
        },
        // 编辑学生确认
        handleConfirm(){
            this.$refs['form'].validate(valid=>{
                if(valid){
                    this.$store.dispatch('updateStudent',this.form).then(res=>{
                    if(res){
                        this.$message({
                            message: '编辑学生成功',
                            type: 'success',
                        })
                        this.dialogFormVisible = false
                    }else(
                        this.$message({
                            message: '编辑学生失败',
                            type: 'error',
                        })
                    )
                    })
                }else{
                    this.$message({
                            message: '请输入正确的数据！',
                            type: 'error',
                        })
                    return false
                }
            })

            
        }

    },
    data() {
        return {
            // 分页页数
            currentPage:1,
            // 每页数量
            pageSize:20,
            // 搜索楼栋
            addressSearch:'',
            // 搜索门牌号
            doorSearch:'',
            // 弹出框
            dialogFormVisible:false,
            AddDialogFormVisible:false,
            // 编辑学生表单
            form:{
                studyNumber: '',
                faculty: '',
                name: '',
                address: '',
                door: '',
                phoneNumber:''
            },
            // 添加学生表单
            addForm:{
                studyNumber: '',
                faculty: '',
                name: '',
                address: '',
                door: '',
                phoneNumber:''
            },
            // 表单验证
            rules: {
                studyNumber:[
                    {required:true,message:'请输入学号',trigger:'blur'}
                ],
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                   
                ],
                faculty: [
                    { required: true, message: '请输入学院', trigger: 'blur' }
                ],
                phoneNumber:[
                    {required:true,message:'请输入电话号码',trigger:'blur'}
                ],
                address:[
                    {required:true,message:'请输入地址',trigger:'blur'}
                ],
                door:[
                    {required:true,message:'请输入门牌号',trigger:'blur'}
                ]
            },

            // 搜索学生信息
            studentSearch:'',
            // 是否搜索学生
            isSearchStudent:false,
            // 按宿舍分组展示学生
            isShowRoomGroup:false,
            // 选项
            options: [{
                value: false,
                label: '按学生显示'
                }, {
                value: true,
                label: '按宿舍显示'
                },
            ],
        };
        
    },
    mounted() {
        // 挂载时获取初始数据
        this.$store.dispatch('getStudentInfo',{pageSize:20,pageIndex:1})
    },
};
</script>
